import type { Effect, Reducer } from 'umi';
import { setAuthority } from '@/utils/authority';
import { queryCurrent, query as queryUsers } from '@/services/auth/user';

export type CurrentUser = {
  head_address?: string;
  name?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  userid?: string;
  role?: any;
  authList?:any;
  authButton:[];

  // avatar?: string;
  // name?: string;
  // title?: string;
  // group?: string;
  // signature?: string;
  // tags?: {
  //   key: string;
  //   label: string;
  // }[];
  // userid?: string;
  // unreadCount?: number;
};

export type UserModelState = {
  currentUser?: CurrentUser;
};

export type UserModelType = {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
};

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      // console.log('------------用户信息-------------')
      // console.log(response)
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      }); 
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      console.log("action.data::::")
      console.log(action.payload.data)
      let data = action.payload.data;
      //保存权限
      const permissions = data.role.permissions;
      setAuthority( permissions.map((item:any)=>item.id));
      // setAuthority(["b845d68a12f34dab88236bd45c8e3f90"])
      const permissionButtonList = data.authList.map((authData:any) => { return authData.parent_permission + ':' + authData.permission });
      data.authButton = permissionButtonList;
      return {
        ...state,
        currentUser: data || {},
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action, 
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
